package cn.com.paycn.ken.utils;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

public class IpUtils
{
  public static String ipAddress(HttpServletRequest request)
  {
    String ip = validIp(request.getHeader("x-forwarded-for"));
    if (StringUtils.isBlank(ip)) {
      ip = validIp(request.getHeader("Proxy-Client-IP"));
    }
    if (StringUtils.isBlank(ip)) {
      ip = validIp(request.getHeader("WL-Proxy-Client-IP"));
    }
    if (StringUtils.isBlank(ip)) {
      ip = request.getRemoteAddr();
    }
    if ("0:0:0:0:0:0:0:1".equals(ip)) {
      ip = "localhost";
    }
    return ip;
  }

  private static String validIp(String ipStr) {
    if (StringUtils.isBlank(ipStr)) {
      return null;
    }
    String[] ips = ipStr.split(",");
    for (String ip : ips) {
      if (!"unknown".equalsIgnoreCase(ip))
        return ip.trim();
    }
    return null;
  }
}